const Base = require('./base.js');

const md5 = require("md5");
const helper = require('think-helper');

module.exports = class extends Base {


    async _initialize() {
        await super._initialize();
    }

    async indexAction() {


        this.assign({
            status: [{key: '0', title: '关闭'}, {key: '1', title: '开启'}]
        })

        await this.display('admin/user/index', {
            options: {
                locals: {
                    layout: '/admin/layout'
                }
            }
        });
    }

    async tableAction() {

        const p = this.query('page') || 1;
        const id = this.post('id');
        const status = this.post('status');
        const keywords = this.post('keywords');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (!helper.isEmpty(keywords)) {
            queryParams = {
                $or: [
                    {username: {$regex: keywords, $options: "$i"}},
                    {email: {$regex: keywords, $options: "$i"}},
                    {mobile: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (!helper.isEmpty(status)) {
            queryParams = Object.assign(queryParams, {status: status});
        }

        //id属性要单独查找,不支持正则表达式
        if (!helper.isEmpty(id)) {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.fail(1001,'没有找到符合条件的数据');
                return;
            }
        }


        console.log(`search queryParams:${JSON.stringify(queryParams)}`);


        /**
         * 获取对模型的引用，如果模型不存在则创建模型并调用初始化操作增加测试数据
         */
        let Model = this.mongoose('User');
        // const pageSize= await this.common.config('LIST_ROWS');
        const pageSize = 10;
        let user = await Model.findPage({
            page: p,
            pageSize: pageSize
        }, '', queryParams, {}, {_id: 'asc'});

        if (think.isEmpty(user.data)){
            this.fail(1001,'没有找到符合条件的数据');
            return;
        }

        this.assign(
            {
                records: user.data,
                pager: super.ajaxPage(p, user.pagination.rowCount, user.pagination.pageSize)
            }
        );
        await this.display('admin/user/table');
    }

    async disableAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('User');
        for (const i of ids) {
            //think.Mongoose.mongoose.Types.ObjectId(i)
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('','禁用用户成功');

    }

    async enableAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('User');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            //this.changeModelField('admin/User', i, 'status', 1);
        }
        this.success('','开启用户成功');
    }

    async deleteAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('User');
        for (const i of ids) {
            // await Model.findByIdAndRemove(i).exec();
            await Model.findUserByIdAndRemove(i);//删除关联数据
        }
        this.success('', '删除用户成功');
    }

    async addAction() {

        if (this.isPost()) {

            const user = this.post;

            if (user.password) {
                user.password = md5(user.password);
            } else {
                delete user.password;
            }

            this.mongoose('User').saveOrUpdate(user);

            this.success('', '保存成功');

        } else {

            if (this.query('id')) {
                const user = await this.mongoose('User').findOne({_id: this.query.id}).lean().exec();
                this.assign( {user: user});
                await this.display('admin/user/add',);
            } else {
                await this.display('admin/user/add');
            }
        }
    }
}